import { createApp } from 'vue'
import App from './App.vue'
import './assets/css/reset.less'
import Card from './components/Card/index.vue'
import Dialog from './components/Dialog/index.vue'
import Loading from './components/Loading'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/antd.css'
import { createPinia, PiniaPluginContext } from 'pinia'

const store = createPinia()

// pinia持久化插件
type Options = {
    key?:string
}
const __piniaKey__ = 'xiaohu'
const setStorage = (key:string, value:any) => {
    localStorage.setItem(key, JSON.stringify(value))
}
const getStorage = (key:string) => (localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key) as string) : {})
const piniaPlugin = (options:Options) => (context: PiniaPluginContext) => { // pinia 持久化插件
    const { store } = context
    const data = getStorage(`${options?.key ?? __piniaKey__}-${store.$id}`)
    store.$subscribe(() => {
        setStorage(`${options?.key ?? __piniaKey__}-${store.$id}`, toRaw(store.$state))
    })
    return {
        ...data,
    }
}
store.use(piniaPlugin({
    key: 'pinia',
}))

let app = createApp(App)
app.use(ElementPlus, {
    locale: zhCn,
})
app.use(Loading).use(Antd).use(store)

// 自定义全局filters
type Filter = {
    format: <T>(str:T) => string
}
declare module '@vue/runtime-core' {
    export interface ComponentCustomProperties {
        $filters:Filter,
        $env:string,
        $loading: {
            show: () => void,
            hide: () => void
        }
    }
}
app.config.globalProperties.$filters = {
    format <T>(str:T):string {
        return `你好~~${str}`
    },
}
app.config.globalProperties.$env = 'dev'

// component 全局组件
app.component('Card', Card).component('Dialog', Dialog).mount('#app')
